package cn.easybuy.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.easybuy.dao.BaseDao;
import cn.easybuy.dao.Order_detailDao;
import cn.easybuy.entity.OrderAndProduct;
import cn.easybuy.entity.Order_detail;
import cn.easybuy.utils.DataSourceUtil;

public class Order_detailDaoImpl extends BaseDao implements Order_detailDao {

	ResultSet rs;
	public Order_detailDaoImpl(Connection conn) {
		super(conn);
		// TODO Auto-generated constructor stub
	}

	@Override
	public int addOrderDetail(Order_detail od) {
		Connection conn = DataSourceUtil.getConnection();
		int num=0;
		PreparedStatement ps=null;
		String sql="INSERT INTO easybuy_order_detail(orderId,productId,quantity,cost) VALUES(?,?,?,?)";
		Object[]objArr={od.getOrderId(),od.getProductId(),od.getQuantity(),od.getCost()};
		try {
			ps=conn.prepareStatement(sql);
			for(int i=0;i<objArr.length;i++){
				ps.setObject(i+1,objArr[i]);
			}
			num=ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DataSourceUtil.closeAll(conn, ps, null);
		}
		return num;
	}
	@Override
	public List<OrderAndProduct> FindOrder_DetailToId(String id) {
		Connection conn = DataSourceUtil.getConnection();
		int num=0;
		PreparedStatement ps=null;
		String sql="SELECT * FROM easybuy_order_detail LEFT JOIN easybuy_product ON easybuy_order_detail.productId=easybuy_product.id where orderId = ?";
		Object[]objArr = {id};
		//调用方法获得结果集
		rs=super.executeQuery(sql,objArr);
		List<OrderAndProduct> list=new ArrayList<OrderAndProduct>();
		try {
			while(rs.next()){
				OrderAndProduct oap=new OrderAndProduct();
				oap.setCost(rs.getFloat("easybuy_order_detail.cost"));
				oap.setFileName(rs.getString("easybuy_product.fileName"));
				oap.setName(rs.getString("easybuy_product.name"));
				oap.setQuantity(rs.getInt("easybuy_order_detail.quantity"));
				list.add(oap);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			DataSourceUtil.closeAll(conn, ps, rs);
		}
		return list;
	}

}
